package yiyuan.code.filedemo.file.service;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import yiyuan.code.filedemo.file.exception.RunMsgException;
import yiyuan.code.filedemo.file.pojo.AjaxReturnBean;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;


/**
 * 通用模块
 *
 * @author zj
 */
@Api(tags = "统一服务-公用服务")
@RestController
@RequestMapping("/api")
public class CommController {

  /**
   * 日志记录
   */
  private static final Logger LOGGER = LoggerFactory.getLogger(CommController.class);


  @Resource
  private FileCommonService fileCommonService;

  /**
   * 上传文件
   *
   * @param file 文件
   * @return fid
   */
  @PostMapping("/file/upload")
  @ApiOperation("文件上传")
  public AjaxReturnBean<String> upload(MultipartFile file) {
    if (file == null) {
      return AjaxReturnBean.createError("请选择上传文件");
    }
    String fileId;
    try {
        fileId = fileCommonService.uploadAsTemp(file);
    } catch (Exception e) {
      LOGGER.error("文件上传失败:{}", e.getMessage(), e);
      return AjaxReturnBean.createError("上传失败");
    }
    return AjaxReturnBean.createSuccess("上传成功", fileId);
  }


  /**
   * 文件下载
   *
   * @param fid 文件主键
   */
  @GetMapping("/file/download/{fid}")
  @ApiOperation("文件下载")
  public void download(HttpServletRequest request, HttpServletResponse response,
                       @PathVariable("fid") String fid) {
    if ("".equals(fid) || fid == null) {
      fileCommonService.downloadToResponse(fid, request, response);
    } else {
      throw new RunMsgException("附件id为空");
    }
  }
}
